//
//  ContactViewController.m
//  HJZWeiBo
//
//  Created by 张德培 on 16/6/3.
//  Copyright © 2016年 蒋晨成. All rights reserved.
//

#import "ContactViewController.h"
#import "MytableView.h"
#import "ContactModel.h"
#import <UIImageView+WebCache.h>
#import "UIImage+Extend.h"

@interface ContactViewController ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource,WBHttpRequestDelegate>
@property (nonatomic,strong)MytableView *tableView;
@property (nonatomic,strong)UITextField *searchTF;
@property (nonatomic,strong)MytableView *searchTableView;
@property (nonatomic,strong)NSMutableArray *modelarray;
@property (nonatomic,strong)NSMutableArray *searcharray;
@property (nonatomic,strong)UIButton *cancelButton;
@property (nonatomic,strong)UIView *backgroundView;
@property (nonatomic,strong)UIView *bgview;

@end

@implementation ContactViewController

- (void)viewWillDisappear:(BOOL)animated {
    self.navigationController.navigationBar.translucent = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title  = @"联系人";
    self.navigationController.navigationBar.translucent = YES;
    // 半透明背景
    self.backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWidth, kHeight)];
    self.backgroundView.backgroundColor = [UIColor blackColor];
    self.backgroundView.alpha = 0.2;
    self.backgroundView.hidden = YES;
    [self.view addSubview:_backgroundView];
    
    
    UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(CancelButtonAction:)];
    self.navigationItem.leftBarButtonItem = cancelButton;
    
    
    
    
    
    
    
    // 搜索栏
    self.searchTF = [[UITextField alloc] initWithFrame:CGRectMake(10,5, kWidth-20, 25)];
    self.searchTF.layer.borderColor = [UIColor grayColor].CGColor;
    self.searchTF.layer.cornerRadius = 2;
    self.searchTF.layer.borderWidth = 0.3;
    self.searchTF.placeholder = @"搜索";
    self.searchTF.delegate = self;
    self.searchTF.leftViewMode = UITextFieldViewModeAlways;
    
    
    // 取消
    self.cancelButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.cancelButton.frame = CGRectMake(kWidth +10,5, 40, 25);
    [self.cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [self.cancelButton addTarget:self action:@selector(animationActon:) forControlEvents:UIControlEventTouchUpInside];
    
    
    // 搜索栏背景
    _bgview = [[UIView alloc]initWithFrame:CGRectMake(0, 64, kWidth+50, 35)];
    _bgview.backgroundColor = [UIColor whiteColor];
    [_bgview addSubview:_searchTF];
    [_bgview addSubview:_cancelButton];
    [self.view addSubview:_bgview];
    
    
    _searchTableView = [[MytableView alloc]initWithFrame:CGRectMake(0, 10, kWidth, kHeight)];
    _searchTableView.tag = 101;
    _searchTableView.delegate = self;
    _searchTableView.dataSource = self;
    _searchTableView.hidden = YES;
    [_backgroundView addSubview:_searchTableView];
    
    
    
    
    
    
    self.tableView = [[MytableView alloc]initWithFrame:CGRectMake(0, 100, kWidth, kHeight-100) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:_tableView];
//    https://api.weibo.com/2/friendships/friends.json
//    https://api.weibo.com/2/search/suggestions/users.json
    
    
    
    
    
    [self netWorkRequestWithUrl:@"https://api.weibo.com/2/friendships/friends.json" withTag:@"list"];
    
}

- (void)netWorkRequestWithUrl:(NSString *)url withTag:(NSString *)tag{
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"];
    NSString *uid = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
    NSDictionary *dic = @{@"uid":uid};
    //    self.currentUrl = url;
//    self.currentTag = tag;
    [WBHttpRequest requestWithAccessToken:accessToken url:url httpMethod:@"GET" params:dic delegate:self withTag:tag];
}
- (void)request:(WBHttpRequest *)request didFinishLoadingWithDataResult:(NSData *)data {
    if ([request.tag isEqualToString:@"list"]) {
        _modelarray = [NSMutableArray array];
        NSDictionary *datadic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *userArray = datadic[@"users"];
        for (NSDictionary *userDic in userArray) {
            ContactModel *model = [[ContactModel alloc]init];
            [model setValuesForKeysWithDictionary:userDic];
            [_modelarray addObject:model];
            
        }
        [_tableView reloadData];
    }else{
        _searcharray = [NSMutableArray array];
        _searcharray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        [_searchTableView reloadData];
        
    }
    
}
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
//    return 10;
//}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView.tag == 101) {
        return _searcharray.count;
    }else{
        return _modelarray.count;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
    }
    if (tableView.tag == 101) {
        cell.textLabel.text = [_searcharray[indexPath.row] objectForKey:@"screen_name"];
        return cell;
    }else{
        ContactModel *model = _modelarray[indexPath.row];
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.profile_image_url]placeholderImage:[UIImage resizedImageWithName:@"avatar_default_small"]];
        cell.textLabel.text = model.name;
        return cell;
    }
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 101) {
        [self.c_delegate sendName:[_searcharray[indexPath.row] objectForKey:@"screen_name"]];
        [self animationActon:nil];
    }else{
        [self.c_delegate sendName:[_modelarray[indexPath.row] name]];
        
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}








- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"];
    NSString *uid = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
    NSDictionary *dic = @{@"q":textField.text,@"uid":uid};
    [WBHttpRequest requestWithAccessToken:accessToken url:@"https://api.weibo.com/2/search/suggestions/users.json" httpMethod:@"GET" params:dic delegate:self withTag:@"search"];
    _searchTableView.hidden = NO;
    _backgroundView.alpha = 1;
    return YES;
    
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    _backgroundView.hidden = NO;
    [self.view bringSubviewToFront:_backgroundView];
    [self.view bringSubviewToFront:_bgview];
    [UIView animateWithDuration:0.5 animations:^{
        self.navigationController.navigationBar.frame = CGRectMake(0, -64, kWidth, 64);
        
        self.bgview.frame = CGRectMake(0, 0, kWidth, 55);
        self.searchTF.frame = CGRectMake(10, 25, kWidth - 20-50, 25);
        self.cancelButton.frame = CGRectMake(kWidth - 50, 25, 40, 25);
        self.tableView.frame = CGRectMake(0, 50, kWidth, kHeight);
    }];
    
    
}

- (void)animationActon:(UIButton *)button{
    _backgroundView.hidden = YES;
    [UIView animateWithDuration:0.5 animations:^{
        self.navigationController.navigationBar.frame = CGRectMake(0, 0, kWidth, 64);
        
        self.bgview.frame = CGRectMake(0, 64, kWidth, 35);
        self.searchTF.frame = CGRectMake(10, 5, kWidth - 20, 25);
        self.cancelButton.frame = CGRectMake(kWidth +10, 5,40, 25);
        self.tableView.frame = CGRectMake(0, 90, kWidth, kHeight);
        self.searchTableView.hidden = YES;
    }];
    self.backgroundView.alpha = 0.3;
    [self.searchTF resignFirstResponder];
    self.searchTF.text = @"";
}
- (void)CancelButtonAction:(UIBarButtonItem *)button{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
